
// SoundRecorderDlg.cpp : implementation file
//

#include "stdafx.h"
#include "SoundRecorder.h"
#include "SoundRecorderDlg.h"
#include "afxdialogex.h"
#include "AudioEngine.h"
#include "FileUtil.h"
#include "DateTimeUtil.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#define KRecordShowOsc 1;

const char* KDataDir="data\\";
const int KVolumeSliderMaxValue=256;
const int KOscilloscopePosY=10;

// CAboutDlg dialog used for App About

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CSoundRecorderDlg dialog




CSoundRecorderDlg::CSoundRecorderDlg(CWnd* pParent /*=NULL*/)
	: CDialogEx(CSoundRecorderDlg::IDD, pParent)
	, m_recordAndPlay(true)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);

	m_playing=false;
	m_recording=false;
	m_audioEngine=new AudioEngine(this);
	m_audioOscilloscope=NULL;
	m_audioOscilloscope=new AudioOscilloscope();
}

CSoundRecorderDlg::~CSoundRecorderDlg()
{
	m_audioOscilloscope->endDraw();
	delete m_audioOscilloscope;
	delete m_audioEngine;
}

void CSoundRecorderDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_MFCBUTTON_Record, m_recordButton);
	DDX_Control(pDX, IDC_MFCBUTTON_Play, m_playButton);
	DDX_Control(pDX, IDC_MFCVSLISTBOX_WaveList, m_waveListBox);
	DDX_Control(pDX, IDC_STATIC_WaveOscilloscope, m_labelWaveOscilloscope);
	DDX_Check(pDX, IDC_CHECK_RecordAndPlay, m_recordAndPlay);
}

BEGIN_MESSAGE_MAP(CSoundRecorderDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_MFCBUTTON_Record, &CSoundRecorderDlg::OnBnClickedMfcbuttonRecord)
	ON_BN_CLICKED(IDC_MFCBUTTON_Play, &CSoundRecorderDlg::OnBnClickedMfcbuttonPlay)
	ON_WM_HSCROLL()
	ON_WM_TIMER()
	ON_BN_CLICKED(IDC_BUTTON_Close, &CSoundRecorderDlg::OnBnClickedButtonClose)
END_MESSAGE_MAP()


// CSoundRecorderDlg message handlers

BOOL CSoundRecorderDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// Add "About..." menu item to system menu.

	m_moduleDataPath = FileUtil::modulePath();
	m_moduleDataPath.append(KDataDir);
	FileUtil::createPath(m_moduleDataPath.c_str());
	CArray<CString> arr;
	FileUtil::getSubFileNameList(arr,m_moduleDataPath.c_str());
	int count=arr.GetCount();
	for (int i=0;i<count;i++)
	{
		CString str=arr.GetAt(i);
		m_waveListBox.AddItem(str);
	}

	//volume slider
	CSliderCtrl* pSlidCtrl=(CSliderCtrl*)GetDlgItem(IDC_SLIDER_Volume);
	pSlidCtrl->SetRange(0,KVolumeSliderMaxValue);
	pSlidCtrl->SetPos(KVolumeSliderMaxValue/2);
	m_audioEngine->setWaveOutVolumePercent(0.5);


	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CSoundRecorderDlg::OnTimer(UINT_PTR nIDEvent)
{
	CDialog::OnTimer(nIDEvent);

	//m_audioOscilloscope->draw();
}

void CSoundRecorderDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CSoundRecorderDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CSoundRecorderDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

void CSoundRecorderDlg::OnBnClickedMfcbuttonRecord()
{
	if(m_recording)
	{
		m_recordButton.SetWindowText("Record");
		m_labelWaveOscilloscope.SetWindowTextA("Wave");
		
		m_audioEngine->stopRecord();
#ifdef KRecordShowOsc
		m_audioOscilloscope->endDraw();
#endif

		//save
		MutableBuffer buffer;
		bool ret=AudioEngine::getWaveHeadedBuffer(m_audioEngine->waveInFormateX(),
			m_audioEngine->waveInBuffer()->buffer(),
			m_audioEngine->waveInBuffer()->bufferSize(),
			&buffer);
		if(ret)
		{
			string fileName;
			fileName.append(DateTimeUtil::currentDateTime14());
			fileName.append(".wav");
			CFile file((m_moduleDataPath+fileName).c_str(),CFile::modeCreate|CFile::modeWrite);
			file.Write(buffer.buffer(),buffer.bufferSize());

			//ui
			m_waveListBox.AddItem(fileName.c_str(),0,0);
		}

		//reset
		m_audioEngine->waveInBuffer()->clear();
	}
	else
	{
		UpdateData();

		m_recordButton.SetWindowText("Save");
		m_labelWaveOscilloscope.SetWindowTextA("Recording...");
		m_audioEngine->startRecord(m_recordAndPlay);

#ifdef KRecordShowOsc
		CRect rect;
		GetClientRect(rect);
		m_audioOscilloscope->draw(this,CPoint((rect.Width()-KOscilloscopeWidth)/2,KOscilloscopePosY));
#endif
	}
	m_recording=!m_recording;
	m_playButton.EnableWindow(!m_recording);
}

void CSoundRecorderDlg::OnBnClickedMfcbuttonPlay()
{
	bool ret=true;

	if(m_playing)
	{
		m_audioEngine->stopPlay();
		m_audioOscilloscope->endDraw();

		m_playButton.SetWindowText("Play");
		m_labelWaveOscilloscope.SetWindowTextA("Wave");
	}
	else
	{
		int index=m_waveListBox.GetSelItem();
		if(index<0)
		{
			AfxMessageBox("Please select a wave file.");
			ret=false;
			return;
		}

		if(ret)
		{
			CString path = m_moduleDataPath.c_str();
		
			CString fileName=m_waveListBox.GetItemText(index);

			CFile file(path+fileName.GetBuffer(),CFile::modeRead);
			unsigned int length=file.GetLength();

			void* out_buffer = malloc(length);
			file.Read(out_buffer,length);

			MutableBuffer waveDataBuffer;
			WAVEFORMATEX structWAVEFORMATEX;
			ret=AudioEngine::getWaveBuffer(structWAVEFORMATEX,&waveDataBuffer,out_buffer,length);
			if(ret)
			{
				//osc
				m_audioOscilloscope->setAudioBuffer(&waveDataBuffer,structWAVEFORMATEX);
				CRect rect;
				GetClientRect(rect);
				m_audioOscilloscope->draw(this,CPoint((rect.Width()-KOscilloscopeWidth)/2,KOscilloscopePosY));

				//audio
				m_audioEngine->setWaveOutFormateX(structWAVEFORMATEX);
				m_audioEngine->addWaveOutBuffer(&waveDataBuffer);
				m_audioEngine->startPlay();

				//button
				m_playButton.SetWindowText("Stop");
				m_labelWaveOscilloscope.SetWindowTextA("Playing...");
			}
			free(out_buffer);
		}

		if(!ret)
		{
			AfxMessageBox("Can't play.");
		}
	}

	if(ret)
	{
		m_playing=!m_playing;

		m_recordButton.EnableWindow(!m_playing);
	}
}

void CSoundRecorderDlg::onAudioPlayFinished()
{
	m_playButton.SetWindowText("Play");
	m_labelWaveOscilloscope.SetWindowTextA("Wave");
	m_playing=false;
	m_recordButton.EnableWindow(!m_playing);
}

void CSoundRecorderDlg::onAudioRecordedBuffer(const void* newBuffer,int newBufferSize,const WAVEFORMATEX& waveFormatex)
{
#ifdef KRecordShowOsc
	m_audioOscilloscope->addAudioBuffer(newBuffer,newBufferSize,waveFormatex);
#endif
}

void CSoundRecorderDlg::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
	// TODO: Add your message handler code here and/or call default
	CSliderCtrl* pSlidCtrl=(CSliderCtrl*)GetDlgItem(IDC_SLIDER_Volume);
	int sliderPos=pSlidCtrl->GetPos();
	m_audioEngine->setWaveOutVolumePercent(sliderPos*1.0/KVolumeSliderMaxValue);

	__super::OnHScroll(nSBCode, nPos, pScrollBar);
}

void CSoundRecorderDlg::OnBnClickedButtonClose()
{
	// TODO: Add your control notification handler code here

	m_audioEngine->stopPlay();
	m_audioEngine->stopRecord();
	//m_audioEngine->setAudioEngineInterface(NULL);
	m_audioOscilloscope->endDraw();

	CDialogEx::OnOK();
}
